/* eslint-disable prettier/prettier */
// import { decode } from 'base-64';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { DeviceEventEmitter, Platform } from 'react-native';
import { decode } from 'base-64';
var Buffer = require('safe-buffer').Buffer;

// Existing buffer code will continue to work without issues:


 
export  const DecodeToken = (data:any) =>{

    const token = data.data;

// JWT 通过 '.' 分割为三部分
const [headerBase64, payloadBase64, signatureBase64] = token.split('.');

// Base64Url 解码函数
const base64UrlDecode = (base64Url:String) => {
  // 将 Base64Url 转换为标准 Base64
    let base64 = base64Url.toString().replace(/-/g, '+').replace(/_/g, '/');

  // 补齐 Base64 字符串的缺失部分（如果长度不是 4 的倍数）
  while (base64.length % 4) {
    base64 += '=';
  }

  // 使用 safe-buffer 的 Buffer 来解码 Base64 并转换为 UTF-8 字符串
  return Buffer.from(base64, 'base64').toString('utf-8');

};

// 解码 Header 和 Payload
// const header = JSON.parse(base64UrlDecode(headerBase64));
// const payload = JSON.parse(base64UrlDecode(payloadBase64));
let cd = base64UrlDecode(payloadBase64);
// 输出解码后的内容
console.log('Header:', headerBase64);
console.log('Payload:', payloadBase64);
console.log('item' + cd);

storeToken(cd);
storeRealToken(token);
console.log('token:============' + headerBase64);
};

 
export  const updateToken = async (data:any) =>{

  const token = data.data;
const [headerBase64, payloadBase64, signatureBase64] = token.split('.');
const base64UrlDecode = (base64Url:String) => {
  let base64 = base64Url.toString().replace(/-/g, '+').replace(/_/g, '/');

while (base64.length % 4) {
  base64 += '=';
}
return Buffer.from(base64, 'base64').toString('utf-8');
};
let cd = base64UrlDecode(payloadBase64);
storeToken2(cd);
storeRealToken(token);
// 输出解码后的内容
let buylist = [''];
try{
  buylist = getbuylist(cd);
} catch{
  console.log('failed!');
}
return buylist;
};
const getbuylist = (cd:string)=>{
  try {
    const token = cd;
    
    if (token) {
      const js = JSON.parse(token);
      let buyarryproductidArray = js.buyarryproductid;
      // 输出结果
       if (buyarryproductidArray[0] === 'no buy')
       {console.log('no item'); return [''];
        } else {
        return buyarryproductidArray;
       }
    } else {
      return [''];
    }
  } catch (error) {
    console.error('Failed to fetch token from AsyncStorage:', error);
    return [''];
  }
}
const storeToken = async (m:string) =>{
  try {

      await AsyncStorage.setItem('token',m);
      DeviceEventEmitter.emit('refreshlogin', true);

  } catch (e){
    //saving error
  }
};
const storeToken2 = async (m:string) =>{
  try {

      await AsyncStorage.setItem('token',m);
     

  } catch (e){
    //saving error
  }
};
const storeRealToken = async (m:string) =>{
  try {

      await AsyncStorage.setItem('rtoken',m);

  } catch (e){
    //saving error
  }
};


export const checkToken = async () => {
  try {
    const token = await AsyncStorage.getItem('token');
    if (token) {
      return true;
    } else {
     return false;
    }
  } catch (error) {
    console.error('Failed to fetch token from AsyncStorage:', error);
    return false;
  }
};

export const getBuy = async () => {
  try {
    const token = await AsyncStorage.getItem('token');
    console.log(token);
    if (token) {
      const js = JSON.parse(token);
      let buyarryproductidArray = js.buyarryproductid;
      // 输出结果
       if (buyarryproductidArray[0] === 'no buy')
       {console.log('no item'); return [''];
        } else {
        return buyarryproductidArray;
       }
    } else {
      return [''];
    }
  } catch (error) {
    console.error('Failed to fetch token from AsyncStorage:', error);
    return [''];
  }
};
